package com.example.stray_animal_management_system.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.stray_animal_management_system.commonu.service.AdoptionService;
import com.example.stray_animal_management_system.commonu.service.AnimalService;
import com.example.stray_animal_management_system.entity.Adoption;
import com.example.stray_animal_management_system.entity.Animal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:   审核领养记录
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/adoptionreview")
@CrossOrigin
public class AdoptionReviewController {

    @Autowired
    private AdoptionService adoptionService;

    @Autowired
    private AnimalService animalService;

    /**
     * 管理员或志愿者查看所有申请
     * */
    @GetMapping("/listAll")
    public Map<String, Object> listAll() {
        List<Adoption> list = adoptionService.list(
                new QueryWrapper<Adoption>().orderByDesc("apply_time")
        );

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", list);
        return res;
    }

    /**
     * 审批接口（管理员 / 志愿者）
     * */
    @PutMapping("/review")
    public Map<String, Object> review(@RequestBody Map<String, Object> payload) {
        Map<String, Object> res = new HashMap<>();
        Integer id = (Integer) payload.get("id");
        Integer status = (Integer) payload.get("status"); // 1=通过, 2=驳回
        String rejectReason = (String) payload.getOrDefault("rejectReason", "");

        Adoption adoption = adoptionService.getById(id);
        if(adoption == null) {
            res.put("code", 404);
            res.put("msg", "申请不存在");
            return res;
        }

        adoption.setStatus(status);
        adoption.setReviewTime(LocalDateTime.now());
        if(status == 1) {
            // 审核通过 → 已领养
            animalService.update(
                    new UpdateWrapper<Animal>()
                            .eq("id", adoption.getAnimalId())
                            .set("status", 1) // 已领养
            );
        } else if(status == 2) {
            // 审核驳回 → 待领养
            adoption.setRejectreason(rejectReason);
            animalService.update(
                    new UpdateWrapper<Animal>()
                            .eq("id", adoption.getAnimalId())
                            .set("status", 0) // 待领养
            );
        }

        adoptionService.updateById(adoption);
        res.put("code", 200);
        res.put("msg", status == 1 ? "审核通过" : "已驳回");
        return res;
    }



}
